#include <iostream>
#include <string.h>
using std::cout;
using std::endl;

class String{
public:
    String()
    :_pstr(new char[1]())
    {
        cout << "string()" << endl;
    }
    
    ~String(){
        cout << "~string()" << endl;
        delete[] _pstr;
        _pstr = nullptr;
    }

    String(const char * pstr)
    :_pstr(new char[strlen(pstr) + 1]())
    {
        strcpy(_pstr, pstr);
        cout << "String(const char *)" << endl;
    }
    
    String(const String & rhs):
    String(rhs._pstr)
    {
        cout << "String(const String&)" << endl;
    }

    String & operator=(const String & rhs){
        if(this != &rhs){
            delete _pstr;
            _pstr = new char[strlen(rhs._pstr) + 1];
            strcpy(_pstr, rhs._pstr);
        }
        return *this;
    }

    bool empty() const{
        return size() == 0;
    }

    int size() const{
        return strlen(_pstr);
    }

    const char * c_str() const{
        return _pstr;
    }

    String & append(const String & rhs){
        const int len = strlen(rhs._pstr) + strlen(_pstr);
        char* temp = new char[len + 1];
        strcpy(temp, _pstr);
        strcat(temp, rhs._pstr);
        delete[] _pstr;
        _pstr = temp;
        return *this;
    }

    String & append(const char * pstr){
       //return append(pstr);  // 会反复调用
       String temp(pstr);
       return append(temp);
    }

private:
    char * _pstr;
};

int main() {
    cout << "----- 测试1：基础构造 -----" << endl;
    String s1;                     // 默认构造
    cout << "s1.empty(): " << s1.empty() << endl;
    cout << "s1.size(): " << s1.size() << endl;

    cout << "\n----- 测试2：C字符串构造 -----" << endl;
    String s2("Hello");            // const char* 构造
    cout << "s2: " << s2.c_str() << endl;
    cout << "s2.size(): " << s2.size() << endl;

    cout << "\n----- 测试3：拷贝构造 -----" << endl;
    String s3(s2);                 // 拷贝构造
    cout << "s3: " << s3.c_str() << endl;

    cout << "\n----- 测试4：赋值运算符 -----" << endl;
    String s4;
    s4 = s3;                       // 赋值运算
    cout << "s4: " << s4.c_str() << endl;

    cout << "\n----- 测试5：append成员函数 -----" << endl;
    s4.append(" World");           // append(const char*)
    cout << "s4 after append: " << s4.c_str() << endl;

    String s5(" C++");
    s4.append(s5);                 // append(const String&)
    cout << "s4 after append: " << s4.c_str() << endl;

    cout << "\n----- 测试6：链式调用 -----" << endl;
    s4.append("!").append(" 2023"); // 链式调用
    cout << "s4 final: " << s4.c_str() << endl;

    cout << "\n----- 测试结束，析构调用 -----" << endl;
    return 0;
}

